<style scoped>
.expand_span {
  margin-left: 30px;
  color: #909399;
  font-weight: bold;
}

.expand_p {
  margin-top: 10px;
}
</style>

<template>
  <div>
    <el-table :data="adminTable" :header-cell-style="{'text-align':'center'}" ref="adminTable"
              :cell-style="{'text-align':'center'}">
      <el-table-column prop="id" label="id" width="100"/>
      <el-table-column prop="username" label="用户名" width="120"/>
      <el-table-column prop="nickname" label="昵称" width="100"/>
      <el-table-column prop="icon" label="头像" width="100">
        <el-tooltip slot-scope="scope" placement="right" effect="light">
          <div slot="content">
            <el-image style="width: 200px;height: 200px;overflow: hidden;"
                      :src="scope.row.icon" fit="fill"/>
          </div>
          <el-image style="width: 75px;height: 75px;overflow: hidden;border-radius: 50%"
                    :src="scope.row.icon" fit="fill"/>
        </el-tooltip>

      </el-table-column>
      <el-table-column prop="sort" label="序号" width="75"/>
      <el-table-column prop="phone" label="电话号码" width="125"/>
      <el-table-column prop="email" label="邮箱" width="200"/>
      <el-table-column prop="created" label="创建时间" width="100"/>
      <el-table-column prop="updated" label="修改时间" width="100"/>
      <el-table-column prop="isEnable" label="状态" width="150">
        <el-switch slot-scope="scope" v-model="scope.row.isEnable"
                   @change="isEnableSwitchUpdate(scope.row.id,scope.row.isEnable,scope.row.nickname)"
                   :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用"
                   :disabled="scope.row.superAdminstate"/>
      </el-table-column>
      <el-table-column width="150">
        <template slot="header">
          <span>角色</span>
          <el-tooltip placement="top">
            <div slot="content">
              <p>出现“<span class="el-icon-circle-plus"/>”时代表该管理员同为多个角色</p>
            </div>
            <span style="color: black" class="el-icon-question"></span>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <span v-if="scope.row.role.length<=1">{{ scope.row.role[0].name }}</span>
          <el-tooltip v-else placement="left">
            <div slot="content">
              <p v-for="role in scope.row.role">{{ role.name }}</p>
            </div>
            <span>{{ scope.row.role[0].name }} <span class="el-icon-circle-plus"/></span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="primary" circle icon="el-icon-search" @click="dataDrawerOpen(scope.row)"/>
          <el-button type="success" circle icon="el-icon-user-solid" @click="secretDrawerOpen(scope.row)"/>
          <el-popover width="250" placement="right" :ref="'deleteBy'+scope.row.id">
            <p style="text-align: center">确认删除：{{ scope.row.username }}？</p>
            <p style="text-align: center">(将滑动条移至右侧以解锁“确认”)</p>
            <el-slider style="width: 100px;margin: 0 auto" v-model="deleteLine" @change="deletePopoverMaxLine($event)"
                       :show-tooltip="false"/>
            <div style="text-align: center">
              <el-button :disabled="confirmDelete" type="danger" @click="deletePopoverUpdate(scope.row.id)">确认删除
              </el-button>
            </div>
            <el-button style="margin-left: 10px" circle slot="reference" type="danger" icon="el-icon-delete"
                       @click="deletePopoverOpen" :disabled="scope.row.superAdminstate"/>
          </el-popover>
        </template>
      </el-table-column>
    </el-table><!--列表-->

    <div style="display: flex;justify-content: flex-end;margin-right: 100px">
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="page" :page-sizes="[5,10,20,30,40,50]" :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper" :total="total"/>
    </div><!--分页-->

    <el-drawer :visible.sync="dataDrawer" :title="'正在修改：'+dataEditForm.name" ref="update">
      <el-form :model="dataEditForm" :rules="dataRule" style="max-width: 450px" ref="updateForm">
        <el-form-item label="昵称" prop="nickname" label-width="100px">
          <el-input v-model="dataEditForm.nickname" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="头像url" prop="icon" label-width="100px">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9999/zx-resource/resources/upload/image/product"
              :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="handleAvatarChange">
            <img v-if="dataEditForm.icon" :src="dataEditForm.icon" class="avatar" alt="404">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone" label-width="100px">
          <el-input v-model="dataEditForm.phone" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="100px">
          <el-input v-model="dataEditForm.email" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="序号" prop="sort" label-width="100px">
          <el-input v-model="dataEditForm.sort" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="角色" label-width="100px" prop="roleIds">
          <el-select v-model="dataEditForm.roleIds" multiple collapse-tags placeholder="请选择" @change="$forceUpdate()"
                     :disabled="dataEditForm.superAdminstate">
            <el-option v-for="item in roleTable" :key="item.id" :label="item.name" :value="item.id"
                       v-show="item.name!=='超级管理员'"/>
          </el-select>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" style="margin-right: 150px" @click="dataDrawerUpdate">修改</el-button>
          <el-button type="danger" @click="dataDrawerClose">取消</el-button>
        </div>
      </el-form>
    </el-drawer><!--数据修改栏-->

    <el-drawer :visible.sync="secretDrawer" :title="'正在修改账户：'+secretEditForm.name" ref="updateSecret">

      <el-form :model="secretEditForm" :rules="secretRules" style="width: 500px">
        <el-form-item label="账号" prop="username" label-width="100px">
          <el-input v-model="secretEditForm.username" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="密码" prop="password" label-width="100px">
          <el-input v-model="secretEditForm.password" autocomplete="off"/>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" style="margin-right: 150px" @click="secretDrawerUpdate()">修改</el-button>
          <el-button type="danger" @click="secretDrawerClose">取消</el-button>
        </div>
      </el-form>
    </el-drawer><!--账户修改栏-->
  </div>
</template>

<script>
import dataUpdate from "@/views/backState/staff/admin/adminListModule/dataUpdate.vue";

export default {
  name: "adminList",
  components: {
    dataUpdate,
  },
  data() {
    return {
      //页码相关
      page: parseInt(""),//当前页数
      pageSize: parseInt(""),//每页展示数
      total: parseInt(""),//最大数据量
      totalPage: parseInt(""),//最大页码

      //adminTable相关
      adminTable: [],
      roleTable: [],

      //删除窗口相关
      confirmDelete: true,
      deleteLine: 0,

      //数据修改栏相关
      dataDrawer: false,
      dataEditForm: {},
      dataRule: {
        nickname: [
          {required: true, message: "请输入管理员昵称", trigger: "blur"},
          {min: 1, max: 15, message: "昵称长度需在1~15个字符之间", trigger: "blur"}
        ],
        phone: [
          {required: true, message: "请输入电话号码", trigger: "blur"},
          {pattern: /^1[3456789]\d{9}$/, message: "请输入正确的电话号码", trigger: "blur"},
        ],
        email: [
          {pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: "请输入正确的邮箱", trigger: "blur"}
        ],
        roleIds:[
          {required: true, message: "请输入角色", trigger: "blur"},
        ]

      },

      //隐私数据修改栏相关
      secretDrawer: false,
      secretEditForm: {
        id: "",
        username: "",
        password: "",
      },
      secretRules: {
        username: [
          {required: true, message: "请输入新的账户名", trigger: "blur"},
          {max: 15, message: "账户名长度需在1~15个字符之间", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入新的密码", trigger: "blur"},
        ]
      },
    }
  },
  methods: {
    //图片
    handleAvatarChange() {
      let data = this.qs.stringify({"imageUrl": this.dataEditForm.icon})
      let url = "http://localhost:9999/zx-resource/resources/deleteImg"
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, data)
    },
    handleAvatarSuccess(response) {
      this.dataEditForm.icon = response.data.url
    },

    //adminTable相关
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.loadAdmin();
    },//切换每页数量
    handleCurrentChange(pageNum) {
      this.page = pageNum;
      this.loadAdmin();
    },//切换页码

    //加载数据
    loadAdmin() {
      if (isNaN(this.page)) this.page = 1;
      if (isNaN(this.pageSize)) this.pageSize = 5;
      let url = 'http://localhost:9999/zx-ams/admin/list?pageNum=' + this.page + "&PageSize=" + this.pageSize;
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.page = jsonResult.data.page;
          this.pageSize = jsonResult.data.pageSize;
          this.total = jsonResult.data.total;
          this.totalPage = jsonResult.data.totalPage;
          this.adminTable = jsonResult.data.list;
          for (let a = 0; a < this.adminTable.length; a++) {
            let roleId = this.adminTable[a].roleIdString.split(",")
            let roleName = this.adminTable[a].roleNameString.split(",")
            let role = [];
            for (let b = 0; b < roleId.length; b++) {
              if (roleName[b] === "超级管理员") {
                this.adminTable[a].superAdminstate = true;
              }
              let Array = {"id": roleId[b], "name": roleName[b]};
              role.push(Array);
            }
            this.adminTable[a].role = role;
          }
        } else {
          this.$alert(jsonResult.message, '错误', {confirmButtonText: '确定'});
        }
      });
    },//获取admin表数据列表
    loadRole() {
      let url = "http://localhost:9999/zx-ams/role/list"
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).get(url).then((response) => {
        let jsonResult = response.data
        if (jsonResult.state === 200) {
          jsonResult = jsonResult.data;
          this.roleTable = jsonResult;
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
    },//获取role表

    //删除窗口相关
    deletePopoverOpen() {
      this.deleteLine = 0;
      this.confirmDelete = true;
    },//打开Popover组件，delete
    deletePopoverMaxLine(index) {
      if (index !== 100) {
        this.deleteLine = 0;
      }
      this.confirmDelete = index !== 100;
    },//检查删除确认条是否拉到右侧
    deletePopoverUpdate(id) {
      let url = "http://localhost:9999/zx-ams/admin/delete";
      let fromData = this.qs.stringify({"id": id});
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, fromData).then((response) => {
        if (response.data.state === 200) {
          this.$message({message: "删除完毕，正在刷新页面", type: "success"});
          this.loadAdmin();
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
      this.$refs[`deleteBy` + id].doClose();
    },//根据id执行删除并关闭对应的popover删除窗口

    //立即更改管理员数据相关
    isEnableSwitchUpdate(id, is_enable, nickname) {
      let url = "http://localhost:9999/zx-ams/admin/updateIsEnable";
      let formData = this.qs.stringify({"id": id, "isEnable": is_enable});
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, formData).then((response) => {
        if (response.data.state === 200) {
          if (is_enable === 1) {
            this.$message({message: "已启用" + nickname, type: "success"})
          } else {
            this.$message({message: "已禁用" + nickname, type: "warning"})
          }
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
    },//变更admin表is_enable字段

    //数据修改栏相关
    dataDrawerOpen(data) {
      let url = "http://localhost:9999/zx-ams/admin/detail";
      let detailData = this.qs.stringify({"id": data.id})
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, detailData).then((response) => {
        let jsonResult = response.data.data;
        if (response.data.state === 200) {
          this.dataEditForm = jsonResult;
          this.dataEditForm.name = jsonResult.nickname;
          this.dataEditForm.superAdminstate = data.superAdminstate
          this.dataEditForm.roleIds = [];
          let a = jsonResult.roleIdString.split(",");
          for (let i = 0; i < a.length; i++) {
            this.dataEditForm.roleIds[i] = (parseInt(a[i]));
          }
        } else {
          this.$message({message: "获取数据失败，调用本地数据"})
          this.dataEditForm = data;
          this.dataEditForm.name = data.nickname;
        }
      })
      this.dataDrawer = true;

    },//打开修改侧边栏
    dataDrawerUpdate() {
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          let url = "http://localhost:9999/zx-ams/admin/update";
          let formData = this.qs.stringify(this.dataEditForm);
          this.axios.create(
              {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
          ).post(url, formData).then((response) => {
            if (response.data.state === 200) {
              this.$message({message: "数据已修改，正在刷新页面", type: "success"});
              if (this.dataEditForm.id === localStorage.getItem("adminId")) {
                localStorage.setItem("adminNickname", this.dataEditForm.nickname);
                localStorage.setItem("adminIcon", this.dataEditForm.icon);
                location.reload()
              }
              this.loadAdmin();
            } else {
              this.$message({message: response.data.message, type: "error"})
            }
          })
          this.dataDrawerClose();
        }else {
          this.$message({message: "数据尚未符合要求", type: "error"})
        }
      })

    },//确认修改窗口内容并触发closingDrawer
    dataDrawerClose() {
      this.dataDrawer = false;
    },//关闭修改侧边栏

    //账户数据修改栏相关
    secretDrawerUpdate() {
      let formData = this.qs.stringify(this.secretEditForm);
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post("http://localhost:9999/zx-ams/admin/updateAccount", formData).then((response) => {
        if (response.data.state === 200) {
          this.$message({message: "完成修改，自动刷新页面以获取最新内容", type: "success"})
          this.loadAdmin();
        } else {
          this.$message({message: response.data.message, type: "error"})
        }
      })
      this.secretDrawerClose()
    },//提交新账户数据
    secretDrawerOpen(data) {
      let url = "http://localhost:9999/zx-ams/admin/detail"
      let data1 = this.qs.stringify({"id": data.id})
      this.axios.create(
          {'headers': {'Authorization': localStorage.getItem('adminJwt')}}
      ).post(url, data1).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          jsonResult = jsonResult.data;
          this.secretEditForm = jsonResult;
          this.secretEditForm.name = this.secretEditForm.username;
        } else {
          this.$message({message: "获取管理员信息失败，将沿用已获取的信息作为参照", type: "warning"})
          this.secretEditForm = data;
        }
        this.secretEditForm.name = this.secretEditForm.username;
        this.secretDrawer = true;
      })
    },//打开账户修改侧边栏，同时获取对应的数据
    secretDrawerClose() {
      this.secretDrawer = false;
    },//关闭账户修改侧边栏

  },
  mounted() {
    this.loadAdmin();
    this.loadRole();
  }
}
</script>